package qj.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class State {
	int current = -1;
	
	ArrayList<String> states = new ArrayList<String>();
	HashMap<String, Set<String>> transitions = new HashMap<String, Set<String>>();
	HashMap<String, Runnable> actions = new HashMap<String, Runnable>();
	
	public void add(String state) {
		states.add(state);
	}

	public void transition(String s1, String s2) {
		Set<String> set = transitions.get(s1);
		if (set == null) {
			set = new HashSet<String>();
			transitions.put(s1, set);
		}
		set.add(s2);
	}

	public boolean to(String state) {
		if (current() == null || transitions.get(current()).contains(state)) {
			toF(state);
			return true;
		}
		
		return false;
	}

	public void toF(String state) {
		current = states.indexOf(state);
		Runnable action = actions.get(state);
		if (action!=null) {
			action.run();
		}
	}
	
	public void on(String state, Runnable action) {
		actions.put(state, action);
	}

	public String current() {
		try {
			return states.get(current);
		} catch (Exception e) {
			return null;
		}
	}

	public boolean is(String state) {
		return states.get(current).equals(state);
	}

	public boolean down() {
		if (current < states.size() - 1) {
			return to(states.get(current + 1));
		}
		return false;
	}

	public void transition2(String s1, String s2) {
		transition(s1, s2);
		transition(s2, s1);
	}
}
